const webpack = require('webpack')
const WebpackDevServer = require('webpack-dev-server')
const args = process.argv.slice(2)

const configName = `./src/example${args[0]}/webpack.config.js`

const config = require(configName)(`example${args[0]}`)
const devServerOptions = Object.assign({}, config.devServer)
const compiler = webpack(config)

console.log('/* --------------------------- config -----------------------------------*/')
console.log('/* --------------------------- config -----------------------------------*/')
console.log(config)
console.log('/* --------------------------- config -----------------------------------*/')
console.log('/* --------------------------- config -----------------------------------*/')

if (args[1] === 'server') {
  // 更新需要添加
  WebpackDevServer.addDevServerEntrypoints(config, devServerOptions)
  const server = new WebpackDevServer(compiler, devServerOptions)
  const port = devServerOptions.port || 8000
  const host = devServerOptions.host || '127.0.0.1'

  server.listen(port, host, () => {
    console.log(`Starting server on http://${host}:${port}`)
  })
} else {
  compiler.run((err, stats) => {
    // [Stats Object](#stats-object)
    if (err || stats.hasErrors()) {
      // [在这里处理错误](#error-handling)
      console.log(err.toString({
        chunks: false,  // 使构建过程更静默无输出
        colors: true    // 在控制台展示颜色
      }))
      return
    }

    // 处理完成
    console.log(stats.toString({
      chunks: false,  // 使构建过程更静默无输出
      colors: true    // 在控制台展示颜色
    }))
  })
}
